package cn.yikaojiuguo.student.ui.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TimerView extends LinearLayout {

	private boolean flag = false;
	private TextView tv_time;
	private long start;
	private long end;
	private long pauseTime = 0;
	private onMaxTimeListener listener;
	private long maxTime = 0;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (flag) {
				end = System.currentTimeMillis() - start + pauseTime;
				if (listener != null && maxTime != 0 && end >= maxTime) {
					listener.timeOut();
					end = maxTime;
					stop();
				}
				tv_time.setText(toTime(end));
			}
		}
	};
	private Thread timeThread;

	public TimerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView();
	}

	public TimerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	public TimerView(Context context) {
		super(context);
		initView();
	}

	private void initView() {
		tv_time = new TextView(getContext());
		tv_time.setText("00:00.00");
		tv_time.setTextColor(0xffe8e8e8);
		tv_time.setTextSize(22);
		this.addView(tv_time);
	}

	public void start() {
		start = System.currentTimeMillis();
		flag = true;
		timeThread = new Thread(new TimeRunnable());
		timeThread.start();
	}

	public void setTextSize(float size) {
		tv_time.setTextSize(size);
	}

	public void pause() {
		flag = false;
		pauseTime = end;
	}

	public void stop() {
		flag = false;
	}

	public void clear() {
		start = System.currentTimeMillis();
		pauseTime = 0;
		tv_time.setText("00:00.00");
	}

	private String toTime(long start) {
		long millisecond = start % 1000;
		millisecond /= 10;
		start /= 1000;
		long minute = start / 60;
		long second = start % 60;
		minute %= 60;
		return String.format("%02d:%02d.%02d", minute, second, millisecond);
	}

	public long getMilliSecondTime() {
		return end;
	}

	public long getSecondTime() {
		return end / 1000;
	}

	public String getFixedTime() {
		return tv_time.getText().toString();
	}

	private class TimeRunnable implements Runnable {
		@Override
		public void run() {
			while (flag) {
				try {
					// 线程停留10毫秒
					Thread.sleep(10);
					// 每隔10毫秒发送空消息
					handler.sendEmptyMessage(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void setOnMaxTimeListener(onMaxTimeListener listener, long maxTime) {
		this.listener = listener;
		this.maxTime = maxTime;
	}

	public interface onMaxTimeListener {
		void timeOut();
	}

	public void setColor(int color) {
		tv_time.setTextColor(color);
	}

}
